<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<meta name="keyword" content="">

    <link rel="shortcut icon" href="/node-mongodb-native/3.3/img/favicon.png">

    <title>CRUD Operations</title>

    <link rel="stylesheet" href="/node-mongodb-native/3.3/lib/bootstrap.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.3/lib/font-awesome/css/font-awesome.min.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.3/css/mongodb-docs.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.3/css/overrides.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.3/lib/highlight/styles/idea.css" />
<link rel="stylesheet" href="/node-mongodb-native/3.3/lib/bootstrap-toggle/bootstrap-toggle.min.css" type="text/css" />
<link rel="stylesheet" href="/node-mongodb-native/3.3/css/java.css" type="text/css" />


  </head>

  <body>
  
  <section id="container" class="">
      
      <header id="header-db" class="row" role="navigation">
  <div class="header-content">
    <div class="toggle-nav pull-left">
        <i class="fa fa-bars"></i>
        <div class="icon-reorder tooltips" data-original-title="Toggle Navigation" data-placement="bottom"></div>
    </div>
    
    <div class="logo pull-left">
      <a href="https://www.mongodb.com/">
        <img src="https://mongodb.github.io/node-mongodb-native/img/logo-mongodb-header.png", alt="MongoDB.com" />
      </a>
    </div>
    
    <div>
<div class="nav-items pull-right">
  <a href="https://university.mongodb.com" data-toggle="tooltip" data-placement="bottom" title="Free Online Classes">MongoDB University</a>
  <a href="https://www.mongodb.com/try" data-toggle="tooltip" data-placement="bottom" title="Download MongoDB">Downloads</a>
  <a href="https://www.mongodb.com/community" data-toggle="tooltip" data-placement="bottom" title="Get involved with MongoDB">Community</a>
  <a href="https://www.mongodb.com/docs" data-toggle="tooltip" data-placement="bottom" title="The MongoDB Documentation">Docs</a>
  <a href="https://www.mongodb.com/blog" data-toggle="tooltip" data-placement="bottom" title="The MongoDB Blog">Blog</a>
  <div id="search">
<form method="get" action="//www.google.com/search" target="_blank">
    <input type="text" name="searchQuery" size="20" value="" autocomplete="off" placeholder="Search docs">
    <input type="hidden" name="site" value="/node-mongodb-native/3.3">
    <input type="hidden" name="q" value="">
    <label for="searchQuery"><i class="fa fa-search fa-1"></i></label>
</form>
</div>

</div>
</div>

  </div>
</header>


      

      
<aside id="sidebar" class="sidebar">
    <div class="ssidebar nav-collapse">
      <div class="ssidebarwrapper">
        <h3>
          <a class="index-link" href="/node-mongodb-native/3.3/../">MongoDB Node.js Driver</a>
          <a class="version pull-right" href="/node-mongodb-native/3.3">3.3</a>
        </h3>

        
        <ul class="sidebar-menu">
          
          
          
          
          
          
          
          
          
          
          
          

          
          
            
            









  


          
            
            









  


          
            
            









  
    
    
      
      
        
        
        
        
        
        
        
        









  
    
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
    
      
    
  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  
    
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
    
      
    
  


        
          
        
      
    
    
      
    
  


          
            
            









  
    
    
      
      
        
        
        
        
        
        
        
        









  
    
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
    
      
    
  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  
    
    
      
      
        
        
        
        
        
        
        
        









  


        
          
        
      
    
      
      
        
        
        
        
        
        
        
        









  
  
  
  
  
  
  
  

  
    
    
    
      
      
      
        
      
    
    
  
  


        
      
    
    
  


        
      
    
      
      
        
      
    
      
      
    
      
      
    
      
      
    
      
      
    
    
  


          
            
            









  
    
    
      
      
    
    
  


          
            
            









  


          
            
            









  


          
            
            









  


          
            
            









  


          

          

          
            
            
















    <li class="toctree-l1">
    <a href="/node-mongodb-native/3.3/installation-guide/installation-guide/">
        <i class='fa fa-puzzle-piece'></i>
        Installation Guide
    </a>
  </li>


          
            
            
















    <li class="toctree-l1">
    <a href="/node-mongodb-native/3.3/quick-start/quick-start/">
        <i class='fa fa-road'></i>
        Quick Start
    </a>
  </li>


          
            
            
















<li class="toctree-l1 ">
  <a href="/node-mongodb-native/3.3/tutorials/main/" class="">
      <i class='fa fa-thumb-tack'></i>
      <span>Tutorials</span>
      <span class="menu-arrow fa fa-angle-right"></span>
  </a>
    <ul >
        
        
        
        
















<li class="toctree-l2 ">
  <a href="/node-mongodb-native/3.3/tutorials/connect/" class="">
      <i class='fa'></i>
      <span>Connect to MongoDB</span>
      
  </a>
    <ul >
        
        
        
        
















    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/tutorials/connect/authenticating/">
        <i class='fa'></i>
        Authentication
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/tutorials/connect/ssl/">
        <i class='fa'></i>
        SSL Settings
    </a>
  </li>


        
        
    </ul>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/tutorials/collations/">
        <i class='fa'></i>
        Collations
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/tutorials/collections/">
        <i class='fa'></i>
        Collections
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/tutorials/create-indexes/">
        <i class='fa'></i>
        Create Indexes
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/tutorials/crud/">
        <i class='fa'></i>
        CRUD Operations
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/tutorials/projections/">
        <i class='fa'></i>
        Projections
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/tutorials/aggregation/">
        <i class='fa'></i>
        Aggregation
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/tutorials/text-search/">
        <i class='fa'></i>
        Text Search
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/tutorials/geospatial-search/">
        <i class='fa'></i>
        Geospatial Search
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/tutorials/commands/">
        <i class='fa'></i>
        Database Commands
    </a>
  </li>


        
        
        
        
        
















<li class="toctree-l2 ">
  <a href="/node-mongodb-native/3.3/tutorials/gridfs/" class="">
      <i class='fa'></i>
      <span>GridFS</span>
      
  </a>
    <ul >
        
        
        
        
















    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/tutorials/gridfs/streaming/">
        <i class='fa'></i>
        GridFS API
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/tutorials/gridfs/gridstore/">
        <i class='fa'></i>
        Legacy GridStore
    </a>
  </li>


        
        
    </ul>
  </li>


        
        
    </ul>
  </li>


          
            
            













  




<li class="toctree-l1  current">
  <a href="/node-mongodb-native/3.3/reference/main/" class="">
      <i class='fa fa-book'></i>
      <span>Reference</span>
      <span class="menu-arrow fa fa-angle-down"></span>
  </a>
    <ul  class="current">
        
        
        
        
















<li class="toctree-l2 ">
  <a href="/node-mongodb-native/3.3/reference/connecting/" class="">
      <i class='fa'></i>
      <span>Connection Options</span>
      
  </a>
    <ul >
        
        
        
        
















    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/reference/connecting/connection-settings/">
        <i class='fa'></i>
        Connection Settings
    </a>
  </li>


        
        
    </ul>
  </li>


        
        
        
        
        













  




<li class="toctree-l2  current">
  <a href="/node-mongodb-native/3.3/reference/ecmascriptnext/" class="">
      <i class='fa'></i>
      <span>ECMAScript Next</span>
      
  </a>
    <ul  class="current">
        
        
        
        
















    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/reference/ecmascriptnext/connecting/">
        <i class='fa'></i>
        Connecting
    </a>
  </li>


        
        
        
        
        













  




    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/reference/ecmascriptnext/crud/">
        <i class='fa'></i>
        CRUD Operations
    </a>
  </li>


        
        
    </ul>
  </li>


        
        
        
        
        
















<li class="toctree-l2 ">
  <a href="/node-mongodb-native/3.3/reference/management/" class="">
      <i class='fa'></i>
      <span>Management</span>
      
  </a>
    <ul >
        
        
        
        
















    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/reference/management/logging/">
        <i class='fa'></i>
        Logging
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/reference/management/apm/">
        <i class='fa'></i>
        APM
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l3">
    <a href="/node-mongodb-native/3.3/reference/management/sdam-monitoring/">
        <i class='fa'></i>
        Topology Monitoring
    </a>
  </li>


        
        
    </ul>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/reference/cursors/">
        <i class='fa'></i>
        Cursors
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/reference/pool/">
        <i class='fa'></i>
        Pool Design
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/reference/unified-topology/">
        <i class='fa'></i>
        Unified Topology Design
    </a>
  </li>


        
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/reference/faq/">
        <i class='fa'></i>
        Frequently Asked Questions
    </a>
  </li>


        
        
    </ul>
  </li>


          
            
            
















<li class="toctree-l1 ">
  <a href="/node-mongodb-native/3.3/upgrade-migration/main/" class="">
      <i class='fa fa-cog'></i>
      <span>Upgrade Guide</span>
      <span class="menu-arrow fa fa-angle-right"></span>
  </a>
    <ul >
        
        
        
        
















    <li class="toctree-l2">
    <a href="/node-mongodb-native/3.3/upgrade-migration/upgrading/">
        <i class='fa fa-wrench'></i>
        Upgrading to 2.x
    </a>
  </li>


        
        
    </ul>
  </li>


          
            
            
















    <li class="toctree-l1">
    <a href="/node-mongodb-native/3.3/api">
        <i class='fa fa-file-text-o'></i>
        API Documentation
    </a>
  </li>


          
            
            
















    <li class="toctree-l1">
    <a href="https://github.com/mongodb/node-mongodb-native">
        <i class='fa fa-github'></i>
        Source Code
    </a>
  </li>


          
            
            
















    <li class="toctree-l1">
    <a href="/node-mongodb-native/3.3/issues-help/">
        <i class='fa fa-life-ring'></i>
        Issues &amp; Help
    </a>
  </li>


          
            
            
















    <li class="toctree-l1">
    <a href="https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&amp;utm_medium=badge&amp;utm_campaign=pr-badge">
        <img src='https://badges.gitter.im/Join Chat.svg'/>
        
    </a>
  </li>


          
        </ul>
        
    </div>
  </div>
  
</aside>

<div class="option-popup closed hidden" id="optionsVersionsPopup">
<div class="option-header">
  <i class="fa fa-gear"></i>
  <span>OPTIONS</span>
  <i class="fa fa-angle-up pull-right"></i>
</div>
<div class="option-body">
  <ul>
      
      <li>
        <label>Version</label>
        <div class="btn-group btn-group-xs pull-right">
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            Select Version <span class="caret"></span>
          </button>
          <ul class="dropdown-menu" role="menu" id="optionsVersionsMenu">
          </ul>
        </div>
      </li>

   


    

  </ul>
</div>
</div>



      
      <section id="main-content" class="content">
          <section class="main-column pull-left">
            <div class="document">
              <div class="documentwrapper">
                <div class="bodywrapper">
                  <div class="body">

                    <div class="alert alert-info" role="alert">
  Note: You are currently viewing version 3.3 of the Node.js driver documentation.
  <a href="https://www.mongodb.com/docs/drivers/node">Click here</a> for the latest version.
</div>



   
<a class="edit-link" href="https://github.com/mongodb/node-mongodb-native/blob/master/docs/reference/content/reference/ecmascriptnext/crud.md" target="_blank" title="Edit reference/ecmascriptnext/crud.md on GitHub"><i class="fa fa-pencil-square-o"></i></a>










<div class="bc">
<ul>
  
  
  
  
  <li><a href="/node-mongodb-native/3.3/reference/main/">Reference</a> <i class="fa fa-angle-right"></i></li>
  <li><a href="/node-mongodb-native/3.3/reference/ecmascriptnext/">ECMAScript Next</a> <i class="fa fa-angle-right"></i></li>
  <li>CRUD Operations</li>
</ul>
</div>




<h1 id="ecmascript-next-crud">ECMAScript Next CRUD</h1>

<p>Let&rsquo;s take a look at the CRUD operations from the perspective of ESNext. In this guide we will be using the same examples as in the general CRUD specification overview but rewrite them to use the new ESNext features. For all method options refer to the main CRUD tutorial.</p>

<ul>
<li><a href="/node-mongodb-native/3.3/tutorials/crud/">CRUD</a>: CRUD Specification.</li>
</ul>

<p>This reference also omits methods that no longer make sense when using ESNext such as the <code>each</code> and <code>forEach</code> methods.</p>

<h2 id="inserting-documents">Inserting Documents</h2>

<p>The <em>insertOne</em> and <em>insertMany</em> methods exist on the <em>Collection</em> class and are used to insert documents into MongoDB. Code speaks a thousand words so let&rsquo;s see two simple examples of inserting documents.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Insert a single document
    let r = await db.collection('inserts').insertOne({a:1});
    assert.equal(1, r.insertedCount);

    // Insert multiple documents
    r = await db.collection('inserts').insertMany([{a:2}, {a:3}]);
    assert.equal(2, r.insertedCount);
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<p>Let&rsquo;s look at a simple example where we are writing to a replicaset and we wish to ensure that we serialize a passed in function as well as have the server assign the <em>_id</em> for each document.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Insert a single document
    const r = await db.collection('inserts').insertOne({
        a:1,
        b: function() { return 'hello'; }
      }, {
        w: 'majority',
        wtimeout: 10000,
        serializeFunctions: true,
        forceServerObjectId: true
      }
    );

    assert.equal(1, r.insertedCount);
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<p>That wraps up the <em>insert</em> methods. Next let&rsquo;s look at the <em>update</em> methods.</p>

<h2 id="updating-documents">Updating Documents</h2>

<p>The <em>updateOne</em> and <em>updateMany</em> methods exist on the <em>Collection</em> class and are used to update and upsert documents into MongoDB. Let&rsquo;s look at a couple of usage examples.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);
    const col = db.collection('updates');
    let r;

    // Insert multiple documents
    r = await col.insertMany([{a:1}, {a:2}, {a:2}]);
    assert.equal(3, r.insertedCount);

    // Update a single document
    r = await col.updateOne({a:1}, {$set: {b: 1}});
    assert.equal(1, r.matchedCount);
    assert.equal(1, r.modifiedCount);

    // Update multiple documents
    r = await col.updateMany({a:2}, {$set: {b: 1}});
    assert.equal(2, r.matchedCount);
    assert.equal(2, r.modifiedCount);

    // Upsert a single document
    r = await col.updateOne({a:3}, {$set: {b: 1}}, {upsert: true});
    assert.equal(0, r.matchedCount);
    assert.equal(1, r.upsertedCount);
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<h2 id="removing-documents">Removing Documents</h2>

<p>The <em>deleteOne</em> and <em>deleteMany</em> methods exist on the <em>Collection</em> class and are used to remove documents from MongoDB. Let&rsquo;s look at a couple of usage examples.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Get the removes collection
    const col = db.collection('removes');
    let r;

    // Insert multiple documents
    r = await col.insertMany([{a:1}, {a:2}, {a:2}]);
    assert.equal(3, r.insertedCount);

    // Remove a single document
    r = await col.deleteOne({a:1});
    assert.equal(1, r.deletedCount);

    // Remove multiple documents
    r = await col.deleteMany({a:2});
    assert.equal(2, r.deletedCount);
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<h2 id="findoneandupdate-findoneanddelete-and-findoneandreplace">findOneAndUpdate, findOneAndDelete and findOneAndReplace</h2>

<p>The three methods <em>findOneAndUpdate</em>, <em>findOneAndDelete</em> and <em>findOneAndReplace</em> are special commands that allow the user to update or upsert a document and have the modified or existing document returned. They come at a cost because the operations take a write lock for the duration of the operation as they need to ensure the modification is <em>atomic</em>. Let&rsquo;s look at <em>findOneAndUpdate</em> first using an example.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Get the findAndModify collection
    const col = db.collection('findAndModify');
    let r;

    // Insert multiple documents
    r = await col.insert([{a:1}, {a:2}, {a:2}]);
    assert.equal(3, r.result.n);

    // Modify and return the modified document
    r = await col.findOneAndUpdate({a:1}, {$set: {b: 1}}, {
      returnOriginal: false,
      sort: [['a',1]],
      upsert: true
    });
    assert.equal(1, r.value.b);

  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<p>The <em>findOneAndDelete</em> function is especially defined to help remove a document. Let&rsquo;s look at an example of usage.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Get the findAndModify collection
    const col = db.collection('findAndModify');
    let r;

    // Insert multiple documents
    r = await col.insert([{a:1}, {a:2}, {a:2}]);
    assert.equal(3, r.result.n);

    // Remove a document from MongoDB and return it
    r = await col.findOneAndDelete({a:1});
    assert.ok(r.value.b == null);
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<h2 id="bulkwrite">BulkWrite</h2>

<p>The <em>bulkWrite</em> function allows for a simple set of bulk operations to be done in a non <a href="https://en.wikipedia.org/wiki/Fluent_interface">fluent</a> way, as compared with the <em>bulk</em> API discussed next. Let&rsquo;s look at an example.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Get the collection
    const col = db.collection('bulk_write');

    const r = await col.bulkWrite([
        { insertOne: { document: { a: 1 } } },
        { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } },
        { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } },
        { deleteOne: { filter: {c:1} } },
        { deleteMany: { filter: {c:1} } },
        { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}
      ],
      {ordered:true, w:1}
    );
    assert.equal(1, r.insertedCount);
    assert.equal(1, Object.keys(r.insertedIds).length);
    assert.equal(1, r.matchedCount);
    assert.equal(0, r.modifiedCount);
    assert.equal(0, r.deletedCount);
    assert.equal(2, r.upsertedCount);
    assert.equal(2, Object.keys(r.upsertedIds).length);
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<p>This covers the basic write operations. Let&rsquo;s have a look at the Bulk write operations next.</p>

<h2 id="bulk-write-operations">Bulk Write Operations</h2>

<p>The bulk write operations make it easy to write groups of operations together to MongoDB. There are some caveats and to get the best performance you need to be running against MongoDB <em>2.6</em> or higher, which supports the new write commands. Bulk operations are split into <em>ordered</em> and <em>unordered</em> bulk operations. An <em>ordered</em> bulk operation guarantees the order of execution of writes while the <em>unordered</em> bulk operation makes no assumptions about the order of execution. In the Node.js driver the <em>unordered</em> bulk operations will group operations according to type and write them in parallel. Let&rsquo;s have a look at how to build an ordered bulk operation.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Get the collection
    const col = db.collection('bulkops');

    // Create ordered bulk, for unordered initializeUnorderedBulkOp()
    const bulk = col.initializeOrderedBulkOp();
    // Insert 10 documents
    for(let i = 0; i &lt; 10; i++) {
      bulk.insert({a: i});
    }

    // Next perform some upserts
    for(let i = 0; i &lt; 10; i++) {
      bulk.find({b:i}).upsert().updateOne({b:1});
    }

    // Finally perform a remove operation
    bulk.find({b:1}).deleteOne();

    // Execute the bulk with a journal write concern
    const result = await bulk.execute();
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<p>We will not cover the results object here as it&rsquo;s documented in the driver API. The Bulk API handles all the splitting of operations into multiple writes.</p>

<p>There are some important things to keep in mind when using the bulk API and especially the <em>ordered</em> bulk API mode. The write commands are insert, update and remove. They will be serially executed in the order they are added, creating a new operation for each switch in types. If you have the following series of operations,</p>

<pre><code>Insert {a:1}
Update {a:1} to {a:1, b:1}
Insert {a:2}
Remove {b:1}
Insert {a:3}
</code></pre>

<p>This will result in the driver issuing 5 write commands to the server:</p>

<pre><code>Insert Command with {a:1}
Update Command {a:1} to {a:1, b:1}
Insert Command with {a:2}
Remove Command with {b:1}
Insert Command with {a:3}
</code></pre>

<p>If instead you order your operations as follows,</p>

<pre><code>Insert {a:1}
Insert {a:2}
Insert {a:3}
Update {a:1} to {a:1, b:1}
Remove {b:1}
</code></pre>

<p>The write commands issued by the driver will be,</p>

<pre><code>Insert Command with {a:1}, {a:2}, {a:3}
Update Command {a:1} to {a:1, b:1}
Remove Command with {b:1}
</code></pre>

<p>Allowing for a more efficient and faster bulk write operation.</p>

<p>For <em>unordered</em> bulk operations this is not important as the driver sorts operations by type and executes them in parallel.</p>

<p>This covers write operations for MongoDB. Let&rsquo;s look at querying for documents next.</p>

<h2 id="read-methods">Read Methods</h2>

<p>The main methods for querying the database are <em>find</em> and <em>aggregate</em>. In this CRUD tutorial we will focus on <em>find</em>.</p>

<p>The <em>find</em> method returns a cursor that allows us to operate on the data. The <em>cursor</em> also implements the Node.js 0.10.x or higher stream interface, allowing us to pipe the results to other streams.</p>

<p>Let&rsquo;s look at a simple <em>find</em> example that materializes all the documents from a query using the <em>toArray</em> method but limits the number of returned results to 2 documents.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Get the collection
    const col = db.collection('find');

    // Insert multiple documents
    const r = await col.insertMany([{a:1}, {a:1}, {a:1}]);
    assert.equal(3, r.insertedCount);

    // Get first two documents that match the query
    const docs = await col.find({a:1}).limit(2).toArray();
    assert.equal(2, docs.length);
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<p>Next let&rsquo;s take a look at the <em>next</em> method and how we can iterate over the cursor in ECMAScript 6. The new <code>async</code>/<code>await</code> commands allow for what is arguably a much cleaner and easier to read iteration code.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Get the collection
    const col = db.collection('find');

    // Insert multiple documents
    const r = await col.insertMany([{a:1}, {a:1}, {a:1}]);
    assert.equal(3, r.insertedCount);

    // Get the cursor
    const cursor = col.find({a:1}).limit(2);

    // Iterate over the cursor
    while(await cursor.hasNext()) {
      const doc = await cursor.next();
      console.dir(doc);
    }
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>

<h2 id="executing-commands">Executing Commands</h2>

<p>The <code>Db.command</code> method also returns a <code>Promise</code> allowing us to leverage <code>async</code>/<code>await</code> for clear and concise code. Below is an example calling the <code>buildInfo</code> method.</p>

<pre><code class="language-js">const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

const url = 'mongodb://localhost:27017';
const dbName = 'myproject';

(async function() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    console.log(&quot;Connected correctly to server&quot;);

    const db = client.db(dbName);

    // Use the admin database for the operation
    const adminDb = db.admin();

    // Retrieve the build information using the admin command
    await adminDb.command({buildInfo:1})
  } catch (err) {
    console.log(err.stack);
  }

  // Close connection
  client.close();
})();
</code></pre>






<div id="btnv">
  
  <div class="pull-left">
  <a class="navigation prev" href="/node-mongodb-native/3.3/reference/ecmascriptnext/connecting/">
      <i class="fa fa-long-arrow-left"> </i> Connecting
  </a>
  </div>
  
  
  <div class="pull-right">
  <a class="navigation next" href="/node-mongodb-native/3.3/reference/management/">
    Management <i class="fa fa-long-arrow-right"> </i>
  </a>
  
</div>
</div>


</div>
<div class="right-column">
<div class="wrapper">
  
  <div class="toc">
    <span class="toc-header">On this page</span>
    <nav id="TableOfContents">
<ul>
<li><a href="#ecmascript-next-crud">ECMAScript Next CRUD</a>
<ul>
<li><a href="#inserting-documents">Inserting Documents</a></li>
<li><a href="#updating-documents">Updating Documents</a></li>
<li><a href="#removing-documents">Removing Documents</a></li>
<li><a href="#findoneandupdate-findoneanddelete-and-findoneandreplace">findOneAndUpdate, findOneAndDelete and findOneAndReplace</a></li>
<li><a href="#bulkwrite">BulkWrite</a></li>
<li><a href="#bulk-write-operations">Bulk Write Operations</a></li>
<li><a href="#read-methods">Read Methods</a></li>
<li><a href="#executing-commands">Executing Commands</a></li>
</ul></li>
</ul>
</nav>
  </div>
  
</div>
</div>

</div>
</div>
</div>
</section>
</section>

</section>


<script type="text/javascript">
  var DOCUMENTATION_OPTIONS = {
   URL_ROOT:    "/node-mongodb-native/3.3",
   VERSION:     "3.3",
   COLLAPSE_INDEX: false,
   FILE_SUFFIX: '.html',
   HAS_SOURCE:  true
  };
</script>
<script type="text/javascript" src="/node-mongodb-native/3.3/js/jquery.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.3/lib/bootstrap.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.3/js/navbar.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.3/lib/highlight/highlight.pack.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.3/js/scripts.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.3/lib/bootstrap-toggle/bootstrap-toggle.min.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.3/js/java.js"></script>
<script type="text/javascript" src="/node-mongodb-native/3.3/js/toggle-switch.js"></script>

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-29229787-1', 'auto');
  ga('send', 'pageview');
</script>
</body>
</html>

